package com.lyh.dt.aspect;

import com.lyh.dt.server.DtActiveMqBean;
import com.lyh.dt.server.TransactionClient;
import com.lyh.dt.server.TransactionType;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author liuyuhong
 */
@Aspect
@Component
public class DtTransactionAspect implements Ordered {

    private static final Logger logger = LoggerFactory.getLogger(DtTransactionAspect.class);

    @Around("@annotation(com.lyh.dt.annotation.GroupTransaction)")
    public void invoke(ProceedingJoinPoint point) {
        logger.info("执行全局事");
        DtActiveMqBean bean = TransactionClient.threadLocalDt.get();
        String groupId = TransactionClient.threadLocalGroupId.get();
        if(StringUtils.isBlank(groupId)){
            groupId = TransactionClient.createTransactionGroup();
            TransactionClient.threadLocalGroupId.set(groupId);
            bean = TransactionClient.createTransaction(groupId);
            TransactionClient.threadLocalDt.set(bean);
        }
        if(bean == null){
            bean = TransactionClient.createTransaction(groupId);
            TransactionClient.threadLocalDt.set(bean);
        }

        try {
            TransactionClient.addTransactionNum(groupId);
            point.proceed();
            TransactionClient.addTransaction(groupId, TransactionType.COMMIT);
        } catch (Exception e) {
            TransactionClient.addTransaction(groupId, TransactionType.ROLLBACK);
            logger.error("事务异常", e);
        } catch (Throwable throwable) {
            TransactionClient.addTransaction(groupId, TransactionType.ROLLBACK);
            logger.error("事务异常", throwable);
        }
    }


    @Override
    public int getOrder() {
        return 10000;
    }
}
